<template>
  <search-table
    :data="targetSystemList"
    :columns="targetSystemCol"
    :page.sync="queryParams.pageIndex"
    :size.sync="queryParams.pageSize"
    :total="targetSystemTotal"
    :loading="targetSystemListLoading"
    @queryFun="getNewData">
    <template slot="search">
      <Button type="primary" ghost class="md-add-jh" @click="showTransfer(null)">创建靶标系统</Button>
      <Divider type="vertical" style="margin: 10px 0px 10px 10px;" />
      <Input v-model.trim="queryParams.targetName"  clearable placeholder="靶标系统名称" @on-change="searchSystemName" style="width: 180px;margin-left: 15px" />
      <Button class="header-btn" type="primary" ghost style="height: 32px;margin-left: 5px;" @click="refreshSystemList()">
        <i class="el-icon-refresh-right" />
      </Button>
    </template>
    <!--创建镜像"-->

    <Modal
        v-model="addModalData.show"
        :title="`创建${activityType === 'real' ? '实网测试' : activityType === 'crowd' ? '众测' : '仿真对抗'}靶标系统`"
        footer-hide
        class="transfer-modal">
      <p>
        {{ activityType === 'real' ? '实网测试' : activityType === 'crowd' ? '众测' : '仿真对抗' }}活动名称：{{ testActivityName }}
      </p>
      <Transfer
          :data="data"
          v-if="addModalData.show"
          :target-keys="targetKeys"
          :titles="titles"
          filterable
          class="my-transfer"
          @on-change="handleChange"></Transfer>
      <Spin size="large" fix v-show="addModalData.loading"></Spin>
    </Modal>
    <Modal
      v-model="detailModalData.show"
      title="靶标系统详情"
      footer-hide
      class="my-modal">
      <div class="item-table">
        <p>
          <span class='label'>靶标名称</span>
          <span>{{detailInfo.targetName}}</span>
        </p>
        <p>
          <span class='label'>所属单位</span>
          <span>{{detailInfo.institutionName}}</span>
        </p>
        <p v-if="activityType === 'real'">
          <span class='label'>行业</span>
          <span>{{(industryList.find(item => item.dictid === detailInfo.industry) || {}).dictname}}</span>
        </p>
        <p v-if="activityType === 'real'">
          <span class='label'>区域</span>
          <span>{{detailInfo.region}}</span>
        </p>
        <p v-if="activityType === 'real'">
          <span class='label'>地址</span>
          <span>{{(detailInfo.urls && detailInfo.urls.length) ? detailInfo.urls.map(item => item.url).join() : ''}}</span>
        </p>
        <p v-if="activityType === 'real'">
          <span class='label'>IP</span>
          <span>{{(detailInfo.urls && detailInfo.urls.length) ? detailInfo.urls.map(item => item.ip).join() : ''}}</span>
        </p>
        <p v-if="activityType !== 'real'">
          <span class='label'>网络名称</span>
          <span>{{detailInfo.testNetinfoName}}</span>
        </p>
        <p v-if="activityType !== 'real'">
          <span class='label'>网络区域</span>
          <span>{{detailInfo.assetNetworkMeshName}}</span>
        </p>
        <p v-if="activityType !== 'real'">
          <span class='label'>供应商</span>
          <span>{{detailInfo.vendorName}}</span>
        </p>
        <p>
          <span class='label'>创建者</span>
          <span>{{detailInfo.creatorName}}</span>
        </p>
        <p>
          <span class='label'>创建时间</span>
          <span>{{detailInfo.created}}</span>
        </p>
        <p>
          <span class='label'>版本</span>
          <span>{{detailInfo.version}}</span>
        </p>
      </div>
    </Modal>
  </search-table>
</template>
<script>
import {targetSystemCol} from "../configData/targetSystemCol";

import {getIndustryList} from '../logic/assetLogic'
import encryption from '@/libs/encryption.js'
import drawers from '../../components/drawers.vue'
import {queryBusinessSystemList} from '../api/extraTest'
import {queryProduct} from "../api/asset";
import {queryExtraTestTargetLinkList,deleteExtraTestTargetLink,batchAddExtraTestTargetLink } from '../api/extraTestTargetLink'

export default {
  components: {drawers},
  props: {
    activityType: {
      type: String,
      default: ''
    },
    testActivityName: {
      type: String,
      default: ''
    },
    testActivityId: {
      type: String,
      default: ''
    },
  },
  data () {
    return {
      addModalData: {
        show: false,
        loading: true
      },

      data:[],
      targetKeys:[],
      targetList:[],

      currentInfo:{},
      currentExtraTestId:'',
      targetSystemTotal:0,
      targetSystemList:[],

      targetSystemCol:[],
      targetSystemListLoading:false,
      industryList:[],

      systemListLoading:false,
      systemTotal:0,
      detailModalData: {
        show: false
      },
      detailInfo: {},
      queryParams:{
        pageIndex:1,
        pageSize:10
      },
      // 用户信息
      USER_ID: '',
      isRootDesinger: '',
      distributed: false,
      actionButtons: [
            {
              txt: '查看',
              on:{
                click:(data,e) => {
                  this.detailModalData.show = true
                  this.detailInfo = data
                }
              },
            },
            {
              txt: '删除',
              tooltip: true,
              type: 'delete',
              title: '确定要删除这吗？',
              on:{
                click:(data,e) => {
                  this.deleteItem(data.id)
                }
              },
            }
      ],
    }
  },
  computed: {
    titles() {
      return this.activityType === 'real' ? ['可选业务系统', '已选业务系统'] : ['可选资产', '已选资产']
    }
  },
  watch: {


  },
  created () {
    // 获取用户id
    let November = sessionStorage.getItem('November')
    November = JSON.parse(encryption.SelfUseDecrypt(November))
    this.USER_ID = November.userId
    this.isRootDesinger = November.isRootDesinger
    this.distributed = November.distributed
    // this.distributedRange = this.$store.state.user.distributedRange
  },
  mounted () {
    this.targetSystemCol = targetSystemCol(this);
    let getPage = this.$route.query.page ? parseInt(this.$route.query.page) : 1
    this.queryParams.pageIndex = getPage
    this.getNewData()
  },
  methods: {
    init(id){
      this.queryParams = {
        pageIndex: 1,
        pageSize: 10
      }
      this.currentExtraTestId = id;
      this.getNewData();
    },
    getNewData(isRefresh){
      // 列表
      if (!isRefresh) { // 非刷新操作才需要展示等待中的画面
        this.targetSystemListLoading = true
      }
      this.queryParams.extraTestId = this.currentExtraTestId;
      queryExtraTestTargetLinkList(this.queryParams)
        .then(res => {
          if (res.code == 1) {
            this.targetSystemTotal =res.data.total;
            this.targetSystemList = res.data.items
          }
          this.targetSystemListLoading = false
        })
        .catch(err => {
          this.targetSystemListLoading = false
        })
    },
    industryListData(){
      if(!this.industryList.length) getIndustryList(this,'industryList')
    },
    searchSystemName(){
      this.queryParams.pageIndex = 1;
      this.getNewData();
    },
    refreshSystemList(){
      this.queryParams = {
        pageIndex:1,
        pageSize:10,
      }
      this.getNewData()
    },
    handleChange(targetKeys, direction, moveKeys) {
      if (direction === 'right') { // 添加操作
        batchAddExtraTestTargetLink(moveKeys.map(key => {
          let item = this.data.find(item => item.key === key) || {}
          return {
            extraTestId: this.testActivityId,
            targetId: item.key,
            targetName: item.label
          }
        })).then(({ code, message }) => {
          if (code !== 1) {
            this.$Message.warning(message)
            return
          }
          this.targetKeys = targetKeys
          this.$Message.success('创建成功')
          this.getNewData()
        })
      } else { // 移除操作
        let ids = this.targetList.filter(item => moveKeys.includes(item.targetId)).map(item => item.id)
        deleteExtraTestTargetLink(this.testActivityId, ids).then(({ code, message })=>{
          if (code !== 1) {
            this.$Message.warning(message)
            return
          }
          this.targetKeys = targetKeys
          this.$Message.success('删除成功')
          this.getNewData()
        })
      }
    },
    deleteItem(id) {
      deleteExtraTestTargetLink([id]).then(({ code, message }) => {
        if (code !== 1) {
          this.$Message.warning(message)
          return
        }
        this.$Message.success(`删除成功`)
        // 删除后展示当前页，当前页没有数据展示前一页
        this.queryParams.pageIndex = (this.targetSystemList.length === 1 && this.queryParams.pageIndex > 1) ?
          this.queryParams.pageIndex - 1 : this.queryParams.pageIndex;
        this.getNewData();
      }).catch(() => {
        this.$Message.error(`删除异常`)
      })
    },
    showTransfer() {
      this.addModalData = {
        show: true,
        loading: true
      }
      let isReal = this.activityType === 'real'
      let getAllTestTarget = isReal ? queryBusinessSystemList : queryProduct
      Promise.all([
        queryExtraTestTargetLinkList({
          pageIndex: 1,
          pageSize: 2147483646,
          extraTestId: this.testActivityId
        }),
        getAllTestTarget({
          pageIndex: 1,
          pageSize: 2147483646,
        })
      ]).then(res => {
        res.forEach(({ code, message, data = {} }, index) => {
          if (index === 0) { // 当前已有的测试活动
            if (code !== 1) {
              this.targetKeys = []
              return
            }
            this.targetList = data.items || []
            this.targetKeys = this.targetList.map(item => item.targetId)
          } else { // 可选的数据
            if (code !== 1) {
              this.data = []
              return
            }
            this.data = (data.items || []).map(item => {
              return {
                key: item.id,
                label: isReal ? item.name : `${item.name}(${item.version})`
              }
            })
          }
        })
        this.addModalData.loading = false
      }).catch(() => {
        this.addModalData.loading = false
      })
    }
  },
  beforeDestroy () {

  }
}
</script>
<style scoped>
 .item-table {
   display: table;
   width: 100%;
   border: 1px solid #eee;
   table-layout: fixed;
   word-break: break-all;
 }
.item-table p {
  display: table-row;
  line-height: 36px;
  text-align: center;
}
.item-table p span {
  display: table-cell;
  border-bottom: 1px solid #eee;
}
.ios-alert {
  /* position: absolute;
        top: -44px;
        right: -404px; */
  color: orange;
  font-size: 16px;
  cursor: pointer;
}
.too {
  position: absolute;
  left: 113px;
  top: -1px;
}
 .transfer-modal  /deep/ .my-transfer{


     width: 100%;
     height: 450px;
     display: flex;
     justify-content: center;
     align-items: center;
     .ivu-transfer-list {
       width: calc(50% - 20px);
       height: 100%;
     }

 }
 .transfer-modal p {
   width: 100%;
   overflow: hidden;
   text-overflow: ellipsis;
   white-space: nowrap;
   margin-bottom: 10px;
 }


</style>

